/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package midpmpc;
import javax.microedition.io.*;
import java.io.*;
import java.util.Hashtable;
import javax.microedition.lcdui.Display;
import org.j4me.logging.Log;

/**
 *
 * @author vvs
 */
public class MpdClientThread {
StreamConnection mpdConn;
DataInputStream is;
DataOutputStream os;
Mpc m;

    public MpdClientThread(Mpc parent) {
        m=parent;
    }

synchronized public String connect(String addr) throws IOException
{
    mpdConn=(StreamConnection)Connector.open("socket://192.168.0.2:6600");
    is=mpdConn.openDataInputStream();
    os=mpdConn.openDataOutputStream();
    return getLine();

}
synchronized String getLine() throws IOException
{
    byte tb;
    String ret="";
    while ((tb=is.readByte())!='\n')
    {
        ret+=(char)tb;
    }
//    m.message(ret);
//    m.debug(ret);
    return ret;
}
synchronized public MpdResponse sendCmd(String cmd)
{
    String ret = "", ts = "";
    try {
        os.write(cmd.getBytes());
        os.write('\n');
        os.flush();
        while (!((ts = getLine()).startsWith("OK"))) {
            ret += ts;
            ret += '\n';
        }
    }
    catch (IOException exc) {
        Log.error("sendCmd", exc);
//        m.debug(exc.getMessage());
    }
    return new MpdResponse(ret);
}
public void stop() throws IOException
{
    sendCmd("stop");
}
public void play() throws IOException
{
    sendCmd("play");
}
public void pause() throws IOException
{
    sendCmd("pause");
}
public Hashtable status() throws IOException
{
    Hashtable ret =new Hashtable();
    MpdResponse resp=sendCmd("status");
    ret.put("state", resp.getString("state"));
    return ret;
}
}


